package com.qyhl.module_practice.search;

import android.annotation.SuppressLint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeSearchBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_SEARCH)
public class PracticeSearchActivity extends BaseActivity implements PracticeSearchContract.PracticeSearchView {
    @BindView(R2.id.commit_cancel_btn)
    TextView commitCancelBtn;
    @BindView(R2.id.search_keywords)
    EditText searchKeywords;
    @BindView(R2.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R2.id.history_layout)
    RelativeLayout historyLayout;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    private PracticeSearchPresenter mPresenter;

    private String keyWords;

    private List<String> keyHistroy = new ArrayList<>();

    private CommonAdapter commonAdapter;

    private List<PracticeSearchIndexBean> indexList = new ArrayList<>();

    private String instId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_search;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new PracticeSearchPresenter(this);
        instId = getIntent().getStringExtra("id");
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
    }

    private void initView() {
        loadMask.setStatus(LoadingLayout.Success);
        setHistory();

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);

        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeSearchIndexBean>(this, R.layout.practice_item_search, indexList) {
            @Override
            protected void convert(ViewHolder holder, PracticeSearchIndexBean bean, int position) {
                TextView title = holder.getView(R.id.title);
                title.setText(bean.getName());
                if (bean.getType() == 0) {
                    title.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//加粗
                    holder.setVisible(R.id.divider, false);
                } else {
                    title.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    holder.setVisible(R.id.divider, true);
                }
            }
        });

    }


    private void setHistory() {
        keyHistroy.clear();
        List<String> stringList = Hawk.get("practice_histroy");
        if (stringList != null && stringList.size() > 0) {
            historyLayout.setVisibility(View.VISIBLE);
            keyHistroy.addAll(stringList);

            flowlayout.setAdapter(new TagAdapter<String>(keyHistroy) {
                @SuppressLint("SetTextI18n")
                @Override
                public View getView(FlowLayout parent, int position, String str) {
                    TextView tv = (TextView) LayoutInflater.from(PracticeSearchActivity.this).inflate(R.layout.practice_item_histroy,
                            flowlayout, false);
                    tv.setText(str);
                    return tv;
                }
            });
        } else {
            historyLayout.setVisibility(View.GONE);
        }
    }

    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.doSearch(keyWords);
            }
        });

        searchKeywords.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyWords = s.toString();
                if (StringUtils.isNotEmpty(s.toString()) && s.toString().trim().length() > 0) {
                    commitCancelBtn.setText("确定");
                } else {
                    commitCancelBtn.setText("取消");
                }
            }
        });

        searchKeywords.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//按下搜索
                    keyWords = searchKeywords.getText().toString();
                    mPresenter.doSearch(keyWords);
                    hideInput();
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }

        });

        flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                keyWords = keyHistroy.get(position);
                mPresenter.doSearch(keyWords);
                return false;
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                PracticeSearchIndexBean bean = indexList.get(position);

                switch (bean.getType()) {
                    case 0:
                        break;
                    case 1:
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("instId", bean.getActId() + "");
                        bundle.putString("streetId", bean.getId() + "");
                        bundle.putString("title", bean.getName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_STREET_DETAIL,bundle);
                    }
                        break;
                    case 2:
                    {
                        String userName = CommonUtils.getInstance().getUserName();
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getActId() + "");
                        bundle.putString("title", bean.getName() + "");
                        bundle.putString("userName",userName);
                        bundle.putString("instId",instId);
                        RouterManager.router(ARouterPathConstant.PRACTICE_ACT_DETAIL,bundle);
                    }
                        break;
                    default:
                        break;
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void setResult(PracticeSearchBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试！");
        boolean isNew = true;
        if (Hawk.contains("practice_histroy")) {
            List<String> histroyList = Hawk.get("practice_histroy");
            for (int i = 0; i < histroyList.size(); i++) {
                if (histroyList.get(i).equals(keyWords)) {
                    isNew = false;
                }
            }
            if (isNew) {
                histroyList.add(0, keyWords);
                if (histroyList.size() > 10) {
                    List<String> list = histroyList.subList(0, 10);
                    Hawk.put("practice_histroy", list);
                } else {
                    Hawk.put("practice_histroy", histroyList);
                }
                setHistory();
            }
        } else {
            List<String> histroyList = new ArrayList<>();
            histroyList.add(keyWords);
            Hawk.put("practice_histroy", histroyList);
        }


        indexList.clear();
        List<PracticeSearchIndexBean> beanList = new ArrayList<>();
        if (bean.getInst() != null && bean.getInst().size() > 0) {
            beanList.add(new PracticeSearchIndexBean(0, "阵地", "", 0));
            for (int i = 0; i < bean.getInst().size(); i++) {
                beanList.add(new PracticeSearchIndexBean(1, bean.getInst().get(i).getName(), instId, bean.getInst().get(i).getId()));
            }
        }

        if (bean.getAct() != null && bean.getAct().size() > 0) {
            beanList.add(new PracticeSearchIndexBean(0, "服务项目", "", 0));
            for (int i = 0; i < bean.getAct().size(); i++) {
                beanList.add(new PracticeSearchIndexBean(2, bean.getAct().get(i).getName(), instId, bean.getAct().get(i).getId()));
            }
        }

        indexList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();

    }

    @Override
    public void searchError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setStatus(LoadingLayout.Empty);
            loadMask.setEmptyImage(R.drawable.empty_content);
            loadMask.setEmptyText(msg);
        } else {
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @OnClick({R2.id.commit_cancel_btn, R2.id.search_delete, R2.id.history_delete})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.commit_cancel_btn) {
            if (commitCancelBtn.getText().toString().equals("取消")) {
                finish();
            } else {
                keyWords = searchKeywords.getText().toString();
                mPresenter.doSearch(keyWords);
            }
        } else if (id == R.id.search_delete) {
            keyWords = "";
            searchKeywords.setText("");
        } else if (id == R.id.history_delete) {
            new CommonDialog.Builder(PracticeSearchActivity.this)
                    .setTitle("提示", R.color.global_black_lv1)
                    .setMessage("是否确定删除历史记录？", R.color.global_black_lv2)
                    .setPositiveButton("确定", v -> {
                        Hawk.delete("practice_histroy");
                        setHistory();
                    }, R.color.global_base)
                    .setNegativeButton("取消", null, R.color.global_gray_lv2).show();
        }
    }

    private class PracticeSearchIndexBean implements Serializable {
        private int type;

        private String name;

        private String actId;

        private int id;

        PracticeSearchIndexBean(int type, String name, String actId, int id) {
            this.type = type;
            this.name = name;
            this.actId = actId;
            this.id = id;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getActId() {
            return actId;
        }

        public void setActId(String actId) {
            this.actId = actId;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_SEARCH);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_SEARCH);
    }
}
